package com.hisan.freeride.home.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.FileProvider;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.hisan.freeride.R;
import com.hisan.freeride.common.base.AppConfig;
import com.hisan.freeride.common.base.BaseActivity;
import com.hisan.freeride.common.base.BaseFragment;
import com.hisan.freeride.common.callback.NoDialogCallback;
import com.hisan.freeride.common.utils.CacheUtils;
import com.hisan.freeride.common.utils.CollectionUtils;
import com.hisan.freeride.common.utils.utils.MyHandlerUtil;
import com.hisan.freeride.common.view.MyBottomLayout;
import com.hisan.freeride.databinding.MymainBinding;
import com.hisan.freeride.home.fragment.HomeFragment;
import com.hisan.freeride.home.fragment.ReleaseFragment;
import com.hisan.freeride.home.fragment.WoFragment;
import com.hisan.freeride.home.model.UpApp;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;




public class MainActivity extends BaseActivity<MymainBinding> {
    private List<BaseFragment> baseFragments=new ArrayList<>(3);
    private VpAdapter adapter;
    //默认首页
    private int type=0;
    //取消时间
    public static final long TIME_SPACE = 2000;
    private long clickTime;
    private String url="";
    //版本名称
    private String codename = "";
    private int total=0;
    private ProgressDialog pd;

    @Override
    protected int getLayoutId() {
        return R.layout.mymain;
    }


    @Override
    protected void initView() {
        baseFragments.add(HomeFragment.getInstance());
        baseFragments.add(ReleaseFragment.getInstance());
        baseFragments.add(WoFragment.getInstance());
        adapter = new VpAdapter(getSupportFragmentManager(), baseFragments);
        //获取包管理者对象
        PackageManager pm = this.getPackageManager();
        try {
            //获取包的详细信息
            PackageInfo info = pm.getPackageInfo(this.getPackageName(), 0);
            codename = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        mBinding.vp.setOffscreenPageLimit(baseFragments.size());
        mBinding.vp.setAdapter(adapter);
        setCurrentFragment(type);
        mBinding.bnve.setResidAndColor(type);
        mBinding.bnve.setOnCallbackListener(new MyCallBackListener());
        if (CacheUtils.getInstance().getBitmap("resource") != null) {
            mBinding.back.setVisibility(View.VISIBLE);
            mBinding.iamge.setImageBitmap(CacheUtils.getInstance().getBitmap("resource"));
            getData();
        } else {
            getData();
        }
    }

    private void getData(){
        OkGo.<List<Object>>get(AppConfig.indexData)
                .params("model",3)
                .execute(new NoDialogCallback<List<Object>>(this) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<List<Object>> response) {
                        super.onSuccess(response);
                        if (!CollectionUtils.isNullOrEmpty(response.body())){
                            if (isOk(response)){
                                JSONArray jsonArray=new JSONArray(response.body());
                                for (int i=0;i<jsonArray.length();i++){
                                    try {
                                        JSONObject json=jsonArray.getJSONObject(i);
                                        Glide.with(MainActivity.this).load(json.getString("thumbnail")).asBitmap().into(new SimpleTarget<Bitmap>() {
                                            @Override
                                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                                CacheUtils.getInstance().put("resource",resource);
                                                MyHandlerUtil.getHandler().postDelayed(() -> {
                                                    mBinding.homeView.setVisibility(View.GONE);
                                                },5000);
                                            }
                                        });
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }else {
                                mBinding.homeView.setVisibility(View.GONE);
                            }
                        }
                    }

                    @Override
                    public void onError(Response<List<Object>> response) {
                        super.onError(response);
                        mBinding.homeView.setVisibility(View.GONE);
                    }
                });
    }

    @Override
    protected void initEvent() {
        mBinding.back.setOnClickListener(v -> {
            mBinding.homeView.setVisibility(View.GONE);
        });
    }

    //获取版本控制信息
    public void getversion() {
        OkGo.<UpApp>get(AppConfig.Getversion)
                .tag(this)
                .execute(new NoDialogCallback<UpApp>(this){
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<UpApp> response) {
                        super.onSuccess(response);
                        if (!CollectionUtils.isNullOrEmpty(response.body())) {
                            url=response.body().getDownload_url();
                            if (response.body().isUpdate_status()) {
                                if (!codename.equals(response.body().getUpdate_version())) {
                                    if (response.body().isForce_update()) {
                                        forceUpdate(response.body().getUpdate_log());
                                    } else {
                                        normalUpdate(response.body().getUpdate_log());
                                    }
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 强制更新
     *
     * @param appName
     */
    private void forceUpdate(final String appName) {
        getmDialog("版本信息：" + appName,"","强制更新").show();
    }

    @Override
    public void onOk() {
        super.onOk();
        loadNewVersionProgress(url);
    }
    /**
     * 下载新版本程序
     */
    private void loadNewVersionProgress(String uri) {
        if (pd==null) pd = new  ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setProgressNumberFormat("%1d KB/%2d KB");
        pd.setMessage("正在下载更新");
        pd.setCanceledOnTouchOutside(false);
        pd.setCancelable(false);
        pd.show();
        //启动子线程下载任务
        new Thread(){
            @Override
            public void run() {
                try {
                    File file = getFileFromServer(uri, pd);
                    sleep(3000);
                    installApk(file);
                    pd.dismiss(); //结束掉进度条对话框
                } catch (Exception e) {
                    //下载apk失败
                    shoewErrorToast("下载新版本失败");
                    e.printStackTrace();
                }
            }}.start();
    }

    /**
     * 安装apk
     */
    protected void installApk(File file) {
        if(Build.VERSION.SDK_INT>=24) {//判读版本是否在7.0以上
            Uri apkUri = FileProvider.getUriForFile(this, "com.hisan.freeride.fileprovider", file);//在AndroidManifest中的android:authorities值
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
            startActivity(install);
        } else{
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(install);
        }
    }


    /**
     * 从服务器获取apk文件的代码
     * 传入网址uri，进度条对象即可获得一个File文件
     * （要在子线程中执行哦）
     */
    public  File getFileFromServer(String uri, ProgressDialog pd) throws Exception{
        //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            URL url = new URL(uri);
            HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            //获取到文件的大小
            pd.setMax((conn.getContentLength() / 1024));
            InputStream is = conn.getInputStream();
            long time= System.currentTimeMillis();//当前时间的毫秒数
            File file = new File(Environment.getExternalStorageDirectory(), time+"");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len ;
            while((len =bis.read(buffer))!=-1){
                fos.write(buffer, 0, len);
                total+= len;
                //获取当前下载量
                pd.setProgress((total / 1024));
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        }
        else{
            return null;
        }
    }


    @Override
    public void onCancel() {
        super.onCancel();
        if (mDialog.isShowing())mDialog.dismiss();
    }



    /**
     * 正常更新
     *
     * @param update_log
     */
    private void normalUpdate(String update_log) {
        getmDialog("版本信息：" + update_log,"暂不更新","确认更新").show();
    }

    private class MyCallBackListener implements MyBottomLayout.ICallbackListener {
        @Override
        public void click(int id) {
            switch (id) {
                case R.id.shoppingLayout:{
                    mBinding.vp.setCurrentItem(0);
                    break;
                }
                case R.id.moduleLayout:{
                    mBinding.vp.setCurrentItem(1);
                    break;
                }
                case R.id.order_cartLayout:
                    mBinding.vp.setCurrentItem(2);
                    break;
            }
        }
    }


    /**
     * 改变fragment状态
     *
     * @param position
     */
    public void setCurrentFragment(final int position) {
        //不使用切换动画 避免与自定义动画冲突
        mBinding.vp.setCurrentItem(position);
    }
    /**
     * view pager adapter
     */
    class VpAdapter extends FragmentPagerAdapter {
        private List<BaseFragment> data;
        public VpAdapter(FragmentManager fm, List<BaseFragment> data) {
            super(fm);
            this.data = data;
        }
        @Override
        public int getCount() {
            return data == null ? 0 : data.size();
        }
        @Override
        public Fragment getItem(int position) {
            return data == null ? null :data.get(position);
        }
        @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
            super.setPrimaryItem(container,position,object);
        }
        public void destroyItem(ViewGroup container, int position, Object object) {}
    }
    //监听物理返回键（判断侧拉框是否打开）
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        LogUtils.v("xxx",keyCode);
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            exit();
            return false;
        }else {
            return super.onKeyDown(keyCode, event);
        }
    }
    /**
     * if click time space < TIME_SPACE, app will exit
     */
    private void exit() {
        if ((System.currentTimeMillis() - clickTime) > TIME_SPACE) {
            showToast("再点一次退出顺风车");
            clickTime = System.currentTimeMillis();
            return;
        }
        //退出应用
        appManger.AppExit(this);
    }
//
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode==99){
//            mBinding.vp.setCurrentItem(0);
//            mBinding.bnve.setResidAndColor(0);
//        }
//    }

    @Override
    protected void loadData(boolean isRefresh) {
        getversion();
    }


}
